<template>
  <div class="container">
    <div class="header">
      <h1 class="title">我的股票收藏</h1>
      <p class="subtitle">管理您关注的股票投资组合</p>
    </div>

    <div class="stats-bar" v-if="isLoggedIn && favoriteStocks.length > 0">
      <div class="stats-item">
        <div class="stats-number">{{ favoriteStocks.length }}</div>
        <div class="stats-label">收藏股票</div>
      </div>
      <div class="stats-item">
        <div class="stats-number">{{ recentlyAdded }}</div>
        <div class="stats-label">本周新增</div>
      </div>
      <div class="stats-item">
        <div class="stats-number">{{ totalDays }}</div>
        <div class="stats-label">关注天数</div>
      </div>
    </div>

    <div v-if="!isLoggedIn" class="login-prompt">
      <div class="login-icon">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
          <path d="M9 12l2 2 4-4"/>
          <path d="M21 12c0 4.97-4.03 9-9 9s-9-4.03-9-9 4.03-9 9-9c2.38 0 4.53.94 6.12 2.47"/>
        </svg>
      </div>
      <h3>请先登录</h3>
      <p>登录后查看您的股票收藏</p>
      <button @click="checkLoginStatus" class="login-btn">
        立即登录
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
          <path d="m9 18 6-6-6-6"/>
        </svg>
      </button>
    </div>

    <div v-else-if="loading" class="loading">
      <div class="spinner"></div>
    </div>

    <transition-group name="list" tag="div" class="stock-grid" v-else-if="favoriteStocks.length > 0">
      <div
          class="stock-card"
          v-for="stock in favoriteStocks"
          :key="stock.stockSymbol"
          @click="viewStock(stock.stockSymbol)"
      >
        <div class="stock-info">
          <div class="stock-symbol">{{ stock.stockSymbol }}</div>
          <div class="created-date">{{ formatDate(stock.createdAt) }}</div>
        </div>
        <div class="stock-actions" @click.stop>
          <button class="btn btn-view" @click="viewStock(stock.stockSymbol)">
            查看详情
          </button>
          <button class="btn btn-unfavorite" @click="removeFavorite(stock.stockSymbol)">
            取消收藏
          </button>
        </div>
      </div>
    </transition-group>

    <div v-else-if="isLoggedIn" class="empty-state">
      <h3>暂无收藏的股票</h3>
      <p>开始添加您感兴趣的股票吧</p>
    </div>

    <button class="refresh-btn" @click="fetchFavoriteStocks">
      <span class="refresh-text">↻</span>
    </button>

    <transition name="fade">
      <div class="toast" :class="{ 'show': showToast }" v-if="toastMessage">
        {{ toastMessage }}
      </div>
    </transition>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import {getUserStarStocks} from "@/api/user/userget";
import {userCancelStarStock} from "@/api/user/userother";
import router from "@/router";
import { useTokenStore } from '@/stores/token.js'
import toast from "@/utils/toast";
export default {
  name: 'UserStars',
  setup() {
    const tokenStore = useTokenStore()
    const favoriteStocks = ref([])
    const loading = ref(false)
    const showToast = ref(false)
    const toastMessage = ref('')
    const isLoggedIn = ref(false)

    // 检查登录状态
    const checkLoginStatus = () => {
      const hasToken = !!tokenStore.token
      isLoggedIn.value = hasToken
      
      if (!hasToken) {
        toast.warning('请先登录')
        setTimeout(() => {
          router.push('/user/auth')
        }, 1500)
        return false
      }
      return true
    }

    const fetchFavoriteStocks = async () => {
      if (!checkLoginStatus()) return
      
      loading.value = true
      try {
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 800))

        const {data}=await getUserStarStocks();
        favoriteStocks.value = data

        toast.success('数据更新完成')
      } catch (error) {
        toast.error('获取数据失败')
      } finally {
        loading.value = false
      }
    }

    const viewStock = (stockSymbol) => {
      // 实际项目中跳转到股票详情页
      toast.info(`正在跳转到 ${stockSymbol} 详情页`)
      router.push({
        path: '/center/stockInformation',
        query: {
          stockSymbol: stockSymbol,
        }
      })
    }

    const removeFavorite = async (stockSymbol) => {
      if (!checkLoginStatus()) return
      
      try {
        await userCancelStarStock(stockSymbol)
        toast.info(`已取消收藏 ${stockSymbol}`)
        window.location.reload()
      } catch (error) {
        toast.info('操作失败')
      }
    }

    const formatDate = (dateString) => {
      const date = new Date(dateString)
      const now = new Date()
      const diffTime = Math.abs(now - date)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

      if (diffDays === 1) return '昨天'
      if (diffDays <= 7) return `${diffDays}天前`
      if (diffDays <= 30) return `${Math.ceil(diffDays / 7)}周前`

      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
      })
    }

    // const showToastMessage = (message) => {
    //   toastMessage.value = message
    //   showToast.value = true
    //   setTimeout(() => {
    //     showToast.value = false
    //     setTimeout(() => {
    //       toastMessage.value = ''
    //     }, 300)
    //   }, 2500)
    // }

    const recentlyAdded = computed(() => {
      const oneWeekAgo = new Date()
      oneWeekAgo.setDate(oneWeekAgo.getDate() - 7)

      return favoriteStocks.value.filter(stock =>
          new Date(stock.createdAt) > oneWeekAgo
      ).length
    })

    const totalDays = computed(() => {
      if (favoriteStocks.value.length === 0) return 0

      const oldestDate = favoriteStocks.value.reduce((oldest, stock) => {
        const stockDate = new Date(stock.createdAt)
        return stockDate < oldest ? stockDate : oldest
      }, new Date())

      const diffTime = Math.abs(new Date() - oldestDate)
      return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    })

    onMounted(() => {
      // 检查登录状态，如果未登录会自动跳转
      if (checkLoginStatus()) {
        fetchFavoriteStocks()
      }
    })

    return {
      favoriteStocks,
      loading,
      showToast,
      toastMessage,
      isLoggedIn,
      recentlyAdded,
      totalDays,
      fetchFavoriteStocks,
      viewStock,
      removeFavorite,
      formatDate,
      checkLoginStatus
    }
  }
}
</script>

<style scoped>
:global(body) {
  margin: 0;
  padding: 0;
  background: #000000;
}

:global(html) {
  margin: 0;
  padding: 0;
  background: #000000;
}

.container {
  width: 100%;
  margin: 0;
  padding: 40px 20px;
  background: #000000;
  color: #ffffff;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Helvetica Neue', Arial, sans-serif;
  min-height: 100vh;
  box-sizing: border-box;
}

.container > * {
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
}

.header {
  text-align: center;
  margin-bottom: 60px;
  position: relative;
}

.title {
  font-size: 3.5rem;
  font-weight: 200;
  letter-spacing: -0.02em;
  margin-bottom: 16px;
  position: relative;
}

.title::after {
  content: '';
  position: absolute;
  bottom: -8px;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 1px;
  background: #ffffff;
  opacity: 0.3;
}

.subtitle {
  color: #666666;
  font-size: 1.1rem;
  font-weight: 300;
  letter-spacing: 0.02em;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.spinner {
  width: 2px;
  height: 2px;
  background: #ffffff;
  border-radius: 50%;
  animation: pulse 1.5s ease-in-out infinite;
  position: relative;
}

.spinner::before,
.spinner::after {
  content: '';
  position: absolute;
  width: 2px;
  height: 2px;
  background: #ffffff;
  border-radius: 50%;
  animation: pulse 1.5s ease-in-out infinite;
}

.spinner::before {
  left: -6px;
  animation-delay: -0.3s;
}

.spinner::after {
  left: 6px;
  animation-delay: 0.3s;
}

@keyframes pulse {
  0%, 80%, 100% {
    transform: scale(1);
    opacity: 1;
  }
  40% {
    transform: scale(1.5);
    opacity: 0.5;
  }
}

.stock-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 32px;
  animation: fadeIn 0.8s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.stock-card {
  background: rgba(255, 255, 255, 0.03);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 2px;
  padding: 32px;
  position: relative;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  backdrop-filter: blur(20px);
}

.stock-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.stock-card:hover::before {
  opacity: 1;
}

.stock-card:hover {
  background: rgba(255, 255, 255, 0.06);
  border-color: rgba(255, 255, 255, 0.15);
  transform: translateY(-4px);
}

.stock-symbol {
  font-size: 2.2rem;
  font-weight: 300;
  letter-spacing: -0.01em;
  margin-bottom: 12px;
  color: #ffffff;
}

.stock-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
}

.created-date {
  color: #999999;
  font-size: 0.9rem;
  font-weight: 300;
  letter-spacing: 0.02em;
}

.stock-actions {
  display: flex;
  gap: 16px;
}

.btn {
  padding: 12px 24px;
  background: transparent;
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #ffffff;
  border-radius: 1px;
  font-weight: 300;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 0.9rem;
  letter-spacing: 0.02em;
  position: relative;
  overflow: hidden;
}

.btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.05);
  transition: left 0.3s ease;
}

.btn:hover::before {
  left: 0;
}

.btn:hover {
  border-color: rgba(255, 255, 255, 0.4);
  background: rgba(255, 255, 255, 0.05);
}

.btn-view {
  flex: 1;
}

.btn-unfavorite {
  border-color: rgba(255, 255, 255, 0.15);
  color: #cccccc;
}

.btn-unfavorite:hover {
  border-color: rgba(255, 255, 255, 0.3);
  color: #ffffff;
}

.login-prompt {
  text-align: center;
  padding: 120px 20px;
  color: #666666;
}

.login-icon {
  width: 80px;
  height: 80px;
  margin: 0 auto 32px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
}

.login-icon svg {
  width: 32px;
  height: 32px;
  stroke-width: 2;
}

.login-prompt h3 {
  font-size: 1.8rem;
  font-weight: 300;
  margin-bottom: 16px;
  color: #ffffff;
}

.login-prompt p {
  font-size: 1.1rem;
  font-weight: 300;
  opacity: 0.7;
  margin-bottom: 32px;
}

.login-btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 16px 32px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #ffffff;
  border-radius: 1px;
  font-weight: 300;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 1rem;
  letter-spacing: 0.02em;
}

.login-btn:hover {
  background: rgba(255, 255, 255, 0.15);
  border-color: rgba(255, 255, 255, 0.3);
  transform: translateY(-2px);
}

.login-btn svg {
  width: 16px;
  height: 16px;
  stroke-width: 2;
}

.empty-state {
  text-align: center;
  padding: 120px 20px;
  color: #666666;
}

.empty-state h3 {
  font-size: 1.5rem;
  font-weight: 300;
  margin-bottom: 12px;
  color: #ffffff;
}

.empty-state p {
  font-size: 1rem;
  font-weight: 300;
  opacity: 0.7;
}

.stats-bar {
  background: rgba(255, 255, 255, 0.02);
  border: 1px solid rgba(255, 255, 255, 0.06);
  border-radius: 1px;
  padding: 32px;
  margin-bottom: 48px;
  backdrop-filter: blur(20px);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stats-item {
  text-align: center;
  flex: 1;
}

.stats-item:not(:last-child) {
  border-right: 1px solid rgba(255, 255, 255, 0.06);
}

.stats-number {
  font-size: 2rem;
  font-weight: 200;
  color: #ffffff;
  margin-bottom: 8px;
  letter-spacing: -0.01em;
}

.stats-label {
  color: #999999;
  font-size: 0.9rem;
  font-weight: 300;
  letter-spacing: 0.02em;
}

.refresh-btn {
  position: fixed;
  bottom: 40px;
  right: 40px;
  width: 56px;
  height: 56px;
  border-radius: 1px;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  color: #ffffff;
  font-size: 1.2rem;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(20px);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.refresh-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  border-color: rgba(255, 255, 255, 0.2);
  transform: rotate(90deg);
}

.refresh-text {
  font-size: 0.8rem;
  font-weight: 300;
}

.toast {
  position: fixed;
  top: 40px;
  right: 40px;
  background: rgba(255, 255, 255, 0.95);
  color: #000000;
  padding: 16px 24px;
  border-radius: 1px;
  z-index: 2000;
  transform: translateX(100%);
  transition: transform 0.3s ease;
  font-weight: 300;
  letter-spacing: 0.02em;
  backdrop-filter: blur(20px);
}

.toast.show {
  transform: translateX(0);
}

@media (max-width: 768px) {
  .container {
    padding: 20px;
  }

  .stock-grid {
    grid-template-columns: 1fr;
    gap: 24px;
  }

  .title {
    font-size: 2.5rem;
  }

  .stats-bar {
    flex-direction: column;
    gap: 24px;
    padding: 24px;
  }

  .stats-item {
    border-right: none;
    border-bottom: 1px solid rgba(255, 255, 255, 0.06);
    padding-bottom: 16px;
  }

  .stats-item:last-child {
    border-bottom: none;
    padding-bottom: 0;
  }

  .stock-actions {
    flex-direction: column;
  }

  .stock-card {
    padding: 24px;
  }
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

.list-enter-active, .list-leave-active {
  transition: all 0.4s;
}

.list-enter-from, .list-leave-to {
  opacity: 0;
  transform: translateY(20px);
}
</style>